<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/3/29
 * Time: 16:20
 * Desc: 首页继承Base
 */
namespace app\index\controller;
use think\Controller;
use think\Db;
use app\index\controller\Base;
use controller\BasicWechat;
use app\index\service\IndexService;
//use pinyin\Pinyin;

class Index1 extends Base{

    public function _initialize(){
        parent::_initialize();
        $this->url = $this->request->url(true);
        $this->assign('url',$this->url);
    }
//    /**
//     * @Author  lingyun
//     * @Desc    首页
//     */
//    public function index(){
//        $this->redirect(url("Index/mall_index"));
//    }
//    /**
//     * @Author  lingyun
//     * @Desc    进入商城首页
//     */
//    public function index(){
//        return $this->fetch('mall_index');
//    }
//
//    /**
//     * @Author  lingyun
//     * @Desc    获取城市门店列表
//     *          接受经纬度参数将门店按照经纬度排序
//     */
//    public function get_store_list(){
//        $post = input('param.');        //接受经纬度参数
//        //城市
//        $city_key = cookie('city_key');
//        if(empty($city_key)){
//            $ip = request()->ip();
//            //获取当前的城市
//            $result = get_location_city($ip);
//            $pinyin = new Pinyin();             //将中文装换成拼音
//            $city_key = $pinyin->getAllPY($result['msg']);
//
//            cookie('city_key',$city_key,3600*24*30);
//            session('city_key',$city_key);
//        }
//        session('city_key',$city_key);
//
//        $where_store = [
//            'is_deleted'=>0,
//            'status'=>1,
//            'city_key'=>session('city_key')
//        ];
//        if(!empty($post['title'])){
//            $this->assign('title',$post['title']);
//            $where_store['title'] = ['like','%'.$post['title'].'%'];
//        }else{
//            $this->assign('title','');
//        }
//        if(empty($post['lng']) || empty($post['lat'])){
////            halt($where_store);
//            $store_arr = db('store')->where($where_store)->order('dis_order desc')->select();
//        }else{
//            //门店排序
//            $store_arr = db('store')->where($where_store)->order('2*asin(sqrt(pow(sin('.$post["lat"].'-lat/2),2)+cos('.$post["lat"].')*cos(lat)*pow(sin('.$post["lng"].'-lng/2),2)))*6378.137*1000 asc')->select();
//        }
//        $this->assign('store_list',$store_arr);
//        $this->assign('city_key',session('city_key'));
//        return $this->fetch('store_list');
//    }

    /**
     * @Author  lingyun
     * @Desc    门店首页
     * @Desc    门店轮播图片、首次进入门店的会员领取门店关注券、门店推荐商品列表、门店推荐商品的分类
     * @Desc    订单详情表里面的goods_id关联ys_goods的主键  spec_id关联的是
     */
    public function index(){
        $service = new IndexService();
        $coupon = $service->qy_coupon(1);
        //门店id
//        $store_id = input('id');
//        $store_id = 0;
//        if(!empty($store_id)){
//            //门店id
//            session('store_id',$store_id);
//        }
        $store_id = cookie('store_id');
        $where_category = [
            'is_deleted'=>0,
            'is_exp'=>0
        ];
        //顶部导航 -- 商品分类
        $category = db('goods_category')->where($where_category)->select();

        //门店顶部轮播图位
        $where_banner = [
            'a.status'=>1,
            'a.is_deleted'=>0
        ];
        //门店的轮播图片
        $banner = db('banner')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where($where_banner)->order('a.dis_order desc')->field('a.*,b.name,b.price,b.unit,b.pc_banner,b.mo_banner')->select();

        //商品标签
        $goods_label = db('goods_label')->where(['status'=>1,'is_deleted'=>0])->select();
        //门店广告位一
        $where_advert_1 = [
            'a.adp'=>1,
        ];
        //门店广告位一
        $advert_1 = db('advert')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where($where_advert_1)->order('a.id desc')->field('a.*,b.name,b.unit,b.price,b.hot_pc_banner,b.hot_mo_banner,b.subtitle')->limit(1)->find();
        //门店广告位二
        $where_advert_2 = [
            'a.adp'=>2,
        ];
        //门店广告位二
        $advert_2 = db('advert')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where($where_advert_2)->order('a.id desc')->field('a.*,b.name,b.price,b.unit,b.hot_pic,b.subtitle')->limit(1)->find();

        //门店优惠券
        $where_coupon['a.status'] = array('eq',1);
        $where_coupon['a.is_recommend'] = array('eq',1);
        $where_coupon['a.is_deleted'] = array('eq',0);
        if(!empty($store_id) && !empty(session('_user_uid_.uid'))){
            $where_coupon['a.store_id'] = array('eq',$store_id);
//            $coupon = db('store_coupon')->alias('a')->join('ys_user_ycard b','a.id=b.coupon_id','LEFT')->where($where_coupon)->field('a.reduce,a.store_id,a.id,IFNULL(b.coupon_id,0) as is_receive')->limit(2)->select();
            $coupon = db('store_coupon')->alias('a')->where($where_coupon)->field('a.reduce,a.store_id,a.id,(select count(*) from ys_user_ycard where uid='.session("_user_uid_.uid").' and coupon_id=a.id) as is_receive')->limit(2)->select();
        }else{
            $coupon = array();
        }


        //门店推荐商品分类
        //推荐商品分类一位
        $where_category_1 = [
            'is_recommend'=>1
        ];
        //推荐商品二位
        $where_category_2 = [
            'is_recommend'=>2
        ];
        //推荐商品分类
        $recommend_category_1 = db('goods_category')->where($where_category_1)->find();
        $recommend_category_2 = db('goods_category')->where($where_category_2)->find();

        //推荐的商品
//        $cate_id = implode(',',array_values(array_unique(array_column($recommend_category, 'cate_id'))));
        $where_recommend_goods_1 = [
            'a.is_deleted'=>0,
            'a.status'=>1,
            'a.cate_id'=>$recommend_category_1['id'],
        ];
        $where_recommend_goods_2 = [
            'a.is_deleted'=>0,
            'a.status'=>1,
            'a.cate_id'=>$recommend_category_2['id'],
        ];
        //推荐商品一位
        $recommend_goods_1 = db('goods_recommend')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where($where_recommend_goods_1)->field('a.*,b.name,b.unit,b.price,b.subtitle,b.logo')->select();
//        foreach($recommend_goods_1 as $k1 => $v1){
//            $recommend_goods_1[$k1]['goods_label'] = explode(',',$v1['goods_label']);
//        }


        //推荐商品二位
        $recommend_goods_2 = db('goods_recommend')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where($where_recommend_goods_2)->field('a.*,b.name,b.subtitle,b.price,b.unit,b.logo')->select();
//        foreach($recommend_goods_2 as $k2 => $v2){
//            $recommend_goods_2[$k2]['goods_label'] = explode(',',$v2['goods_label']);
//        }

        $uid = session('_user_uid_.uid');
        $user = db('user')->where('uid',$uid)->find();
        $cur_city = db('city')->where('key',cookie('city_key'))->value('value');

//        halt($advert_1);

        $this->assign('category',$category);                     //顶部商品分类导航
        $this->assign('banner',$banner);                         //顶部轮播图
        $this->assign('advert_1',$advert_1);                     //广告位一
        $this->assign('advert_2',$advert_2);                     //广告位二
        $this->assign('coupon',$coupon);                         //门店推荐关注券
        $this->assign('recommend_category_1',$recommend_category_1); //推荐商品分类
        $this->assign('recommend_category_2',$recommend_category_2); //推荐商品分类
        $this->assign('recommend_goods_1',$recommend_goods_1);       //门店推荐商品
        $this->assign('recommend_goods_2',$recommend_goods_2);       //门店推荐商品
        $this->assign('goods_label',$goods_label);               //商品标签
        $this->assign('realname',session('_user_uid_.realname'));                            //会员信息
        $this->assign('cur_city',$cur_city);                    //当前城市

        return $this->fetch('index');
    }

    /**
     * @Author  lingyun
     * @Desc    接受
     */
    public function receive_coupon(){
        $post = input('post.');
        if(session('_user_uid_.uid') == ''){
            $this->error('请先登录',url('Login/loginin'),7);
        }
        $coupon = db('store_coupon')->where('id',$post['id'])->find();
        $data = [
            'store_id'=>$coupon['store_id'],
            'uid'=>session('_user_uid_.uid'),
            'coupon_id'=>$coupon['id'],
            'order_id'=>0,
            'receive_order_id'=>0,
            'type'=>1,          //关注券
            'cat_id'=>$coupon['cat_id'],
            'condition'=>$coupon['condition'],
            'morethan'=>$coupon['morethan'],
            'reduce'=>$coupon['reduce'],
            'use_start_time'=>$coupon['use_start_time'],
            'use_end_time'=>$coupon['use_end_time'],
            'addtime'=>time(),
            'price'=>$coupon['price'],
            'value'=>$coupon['value'],
            'is_used'=>0,
            'status'=>1
        ];
        db('user_ycard')->insert($data);
        db('store_coupon')->where('id',$post['id'])->setInc('send_num',1);      //更新优惠券领取数量
        $this->success('领取成功','');
    }

    /**
     * @Author  lignyun
     * @Desc    门店代金券
     */
    public function cash_coupon_list(){
        $store_id = session('store_id');
        $where_store_coupon = [
            'store_id'=>['eq',$store_id],
            'type'=>['eq',2],
            'status'=>['eq',1],
            'is_deleted'=>['eq',0]
        ];
        $list = db('store_coupon')->where($where_store_coupon)->select();
        $this->assign('list',$list);
        return $this->fetch('cash_coupon_list');
    }

    /**
     * @Author  lignyun
     * @Desc    购买
     */
    public function post_cash_coupon(){
        $id = input('id');      //代金券id
        $where = [
            'uid'=>['eq',session('_user_uid_.uid')],
            'id'=>['eq',$id]
        ];
        $coupon = db('store_coupon')->where('id',$id)->find();
        $result = db('cash_coupon_list')->where($where)->field('count(*) as count,uid,cash_coupon_id')->find();
        if(!empty($result)){
            if($result['count'] >= $coupon['create_num']){
                $this->error('每人限购数量已达上限，不能再次购买',url('Index/store')."?id=".session('store_id'));
            }
        }
        $this->assign('coupon',$coupon);
        return $this->fetch('post_cash_coupon');
    }

    /**
     * @Author  lignyun
     * @Desc    余额购买代金券
     */
    public function buy_cash_coupon(){
        $post = input('param.');
        $uid = session("_user_uid_.uid");
        $where_user['uid'] = ['eq',$uid];
        //会员信息
        $member = db('user')->where($where_user)->field('uid,user_money,realname,level_point,pay_points')->find();

        $where_coupon['id'] = ['eq',$post['id']];
        //代金券信息
        $coupon = db('store_coupon')->where($where_coupon)->find();

        if($coupon['price']>$member['user_money']){
            $this->error('您当前的余额已不足，请选择其他付款方式','');
        }
        $data_arr = [
            'order_sn'=>create_order_sn($uid),
            'uid'=>$uid,
            'cash_coupon_id'=>$post['id'],
            'store_id'=>session('store_id'),
            'pay_time'=>time(),
            'pay_type'=>$post['pay_type'],
            'pay_status'=>1,
            'price'=>$coupon['price'],
            'remark'=>'支付成功',
            'addtime'=>time()
        ];
        db('cash_coupon_list')->insert($data_arr);
        $data_arr1 = [
            'uid'=>$uid,
            'store_id'=>session('store_id'),
            'order_sn'=>$data_arr['order_sn'],
            'pay_time'=>time(),
            'pay_status'=>1,
            'pay_type'=>3,
            'amount'=>$coupon['price'],
            'cur_amount'=>$member['user_money'] - $coupon['price'],
            'sign'=>2,
            'charge_cn'=>'购买代金券',
            'addtime'=>time()
        ];
        db('user_wallet_log')->insert($data_arr1);
        $where_point_rule['id'] = ['eq',2];
        $point_rule = db('sys_point')->where($where_point_rule)->find();
        //变更的积分
        $point = ceil($coupon['price']/10);
        $data_arr2 = [
            'uid'=>$uid,
            'store_id'=>session('store_id'),
            'uidtype'=>1,
            'signid'=>2,
            'type'=>1,
            'point'=>$point,
            'curpoint'=>$member['pay_points']+$point,
            'type_cn'=>'购买代金券赠送积分',
            'remark'=>'购买代金券赠送积分',
            'addtime'=>time(),
        ];
        db('user_point_log')->data($data_arr2)->insert();
        $cur_level_point = $member['level_point']+$point;
        $cur_pay_point = $member['pay_points']+$point;
        $point_rule = db('sys_level')->select();
        $level = userLevel($point_rule,$cur_level_point);
        $data_arr3 = [
            'uid'=>$uid,
            'user_money'=>$member['user_money']-$coupon['price'],
            'level_point'=>$cur_level_point,
            'pay_points'=>$cur_pay_point,
        ];
        db('user')->data($data_arr3)->update();
        $this->success('支付成功','');
    }

    /**
     * @Author  lingyun
     * @Desc    搜索
     */
    public function search(){
        $key = input('key');
        //搜索结果
        $goods = db('goods')->where('name','like','%'.$key.'%')->paginate(2,false,['query'=>request()->param()]);
        //商品顶级分类
        $category = db('goods_category')->where(['status'=>1,'is_deleted'=>0,'is_exp'=>0])->select();
        //扩展分类
        $exp_category = db('goods_category')->where(['status'=>1,'is_deleted'=>0,'is_exp'=>1])->select();

        $page = $goods->render();
        $this->assign('page',$page);
        $this->assign('goods',$goods);
        $this->assign('category',$category);
        $this->assign('exp_category',$exp_category);
        $this->assign('city',cookie('city'));
        $this->assign('realname',session('realname'));
        $this->assign('cate_id',$category[0]['id']);

        return $this->fetch('search');
    }

    /**
     * @Author  lingyun
     * @Desc    首页更多优惠券
     */
    public function more_coupon(){
        $store_id = cookie('store_id');
        if(empty(session('_user_uid_.uid'))){
            $this->redirect('Login/loginin');
        }
        if(empty($store_id)){       //没有选中门店 -- 区选择门店
            $this->redirect('Changestore/index');
        }
        $map_arr = [
            'store_id'=>$store_id,
            'type'=>1,
            'status'=>1,
            'is_deleted'=>0
        ];
        $coupon = db('store_coupon')->where($map_arr)->field('id,morethan,reduce,(select count(*) from ys_user_ycard where uid='.session("_user_uid_.uid").' and coupon_id=ys_store_coupon.id) as is_received')->select();

        $this->assign('coupon',$coupon);

        return $this->fetch('more_coupon');
    }

    /**
     * @Author  lingyun
     * @Desc    获取会员权益
     * 2018-03-23
     */
    public function get_qy_coupon(){
        $uid = session('_user_uid_.uid');
        if(empty($uid)){        //先去登录
            return json(['code'=>-1,'msg'=>'您好没有登录，请先去登录']);
        }
        $service = new IndexService();
        $res = $service->get_qy_coupon(2);      //获取权益优惠券

        if($res>0){
            return json(['code'=>1,'msg'=>'领取成功']);
        }else{
            return json(['code'=>0,'msg'=>'领取失败']);
        }
//        $data = [];                 //组合入库数据
//        foreach($coupon as $k=>$v){     //组合入库数据
//            $data[$k]['store_id'] = $v['store_id'];
//            $data[$k]['coupon_id'] = $v['id'];
//            $data[$k]['uid'] = $uid;
//            $data[$k]['type'] = 3;
//            $data[$k]['cat_id'] = $v['cat_id'];
//            $data[$k]['condition'] = $v['condition'];
//            $data[$k]['morethan'] = $v['morethan'];
//            $data[$k]['reduce'] = $v['reduce'];
//            $data[$k]['use_start_time'] = $v['use_start_time'];
//            $data[$k]['use_end_time'] = $v['use_end_time'];
//            $data[$k]['addtime'] = time();
//            $data[$k]['price'] = $v['price'];
//            $data[$k]['value'] = $v['value'];
//            $data[$k]['is_used'] = 0;
//            $data[$k]['status'] = 1;
//        }
//
//        $res = db('user_ycard')->insertAll($data);      //批量新增


    }

}
